﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RPCServer.Core
{
    class MBufferManager
    {
        readonly byte[] _buffer;
        readonly int _bufferSize;
        readonly ConcurrentStack<int> _emptyOffsets;

        public MBufferManager(int bufferSize, int capcity)
        {
            _bufferSize = bufferSize;
            capcity -= capcity % bufferSize;
            _buffer = new byte[capcity];

            _emptyOffsets = new ConcurrentStack<int>();
            for (int i = 0; i < capcity / bufferSize; i++)
            {
                _emptyOffsets.Push(i * bufferSize);
            }
        }

        public MBuffer ApplyBuffer()
        {
            MBuffer buffer;
            if (_emptyOffsets.TryPop(out int offset))
            {
                buffer = MObjectManager.Instance.GetItem<MBuffer>();
                buffer.SetBuffer(_buffer, offset, _bufferSize);
            }
            else
            {
                LogManager.Instance.LogError("Buffer 空间不足！");
                buffer = MBuffer.EmptyBuffer;
            }
            return buffer;
        }

        public void ReturnBuffer(MBuffer buffer)
        {
            _emptyOffsets.Push(buffer.Orign);
            MObjectManager.Instance.RecycleItem(buffer);
        }
    }
}
